/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bizentity.json.operation;

import static com.fasterxml.jackson.core.JsonToken.END_ARRAY;
import static com.fasterxml.jackson.core.JsonToken.FIELD_NAME;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;
import com.inspur.edp.bef.bizentity.common.BizEntityJsonConst;
import com.inspur.edp.cef.designtime.api.collection.BaseList;
import com.inspur.edp.cef.designtime.api.json.SerializerUtils;
import java.util.HashMap;

public abstract class RequestChildElementsDeserializer<T extends BaseList<String>> extends
    JsonDeserializer<HashMap<String, T>> {

  public String currentKey;

  @Override
  public HashMap<String, T> deserialize(JsonParser parser, DeserializationContext ctxt) {
    HashMap<String, T> hashMap = createHashMap();
    if (SerializerUtils.readNullObject(parser)) {
      return hashMap;
    }
    SerializerUtils.readStartArray(parser);
    JsonToken tokentype = parser.getCurrentToken();
    if (tokentype != END_ARRAY) {
      while (parser.getCurrentToken() == tokentype) {
        readHashMap(hashMap, parser);
      }
    }
    SerializerUtils.readEndArray(parser);

    return hashMap;
  }

  private void readHashMap(HashMap<String, T> hashMap, JsonParser parser) {
    SerializerUtils.readStartObject(parser);
    while (parser.getCurrentToken() == FIELD_NAME) {
      String propName = SerializerUtils.readPropertyName(parser);
      readPropertyValue(hashMap, propName, parser);
    }
    SerializerUtils.readEndObject(parser);
  }

  private void readPropertyValue(HashMap<String, T> hashMap, String propName,
      JsonParser jsonParser) {
    switch (propName) {
      case BizEntityJsonConst.RequestChildElementKey:
        currentKey = SerializerUtils.readPropertyValue_String(jsonParser);
        break;
      case BizEntityJsonConst.RequestChildElementValue:
        T collection = createValueType();
        SerializerUtils.readArray(jsonParser, new StringDeserializer(), collection, true);
        hashMap.put(currentKey, collection);
        break;
    }
  }

  abstract HashMap<String, T> createHashMap();

  abstract T createValueType();
}
